package cn.tedu.egmvc2.controller;

import cn.tedu.egmvc2.base.response.JsonResult;
import cn.tedu.egmvc2.mapper.UserMapper;
import cn.tedu.egmvc2.pojo.dto.UserInsertParam;
import cn.tedu.egmvc2.pojo.dto.UserUpdateParam;
import cn.tedu.egmvc2.pojo.entity.User;
import cn.tedu.egmvc2.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
@Validated
@Api(tags = "用户")
@RestController//组合注解相当于@controller+@ResponseBody
@RequestMapping("/v1/user/")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    //用户将：用户名、密码、昵称 数据传递给服务端，服务端处理请求并将数据存入数据表。
    @ApiOperation(value = "添加用户")
    @ApiOperationSupport(order = 10)
    @PostMapping("add")

    public JsonResult insert(@RequestBody @Validated UserInsertParam userInsertParam){
        //改造返回值
    //public String insert(UserInsertParam userInsertParam){
        System.out.println("接受到的数据："+userInsertParam);
        User user = new User();
        BeanUtils.copyProperties(userInsertParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
         int i=userMapper.insert(user);
         //return "新增"+i+"条数据";
        return JsonResult.ok();
    }

    //查询用户列表
    @ApiOperation(value = "查看信息")
    @ApiOperationSupport(order = 20)
    @GetMapping("list")
//    public void  select(){
    public JsonResult  select(){
        List<UserListVO> list = userMapper.list();
        for (UserListVO userListVO: list){
            System.out.println(userListVO);
        }
        return JsonResult.ok(list);
    }

    //删除指定用户
    @ApiOperation(value = "删除用户")
    @ApiOperationSupport(order = 30)
    @PostMapping("del")
    @ApiImplicitParam(name = "id", value = "用户编号", required = true,dataType = "int")
    //public String delete(Integer id){
    public JsonResult delete(@Range(min = 1,max = 100,message = "用户编号必须在1-100之间") @RequestParam Integer id){
        int i =userMapper.delete(id);
        //return "删除了"+i+"条";
        return JsonResult.ok();
    }
    //更改记录
    @ApiOperation(value = "更新用户信息")
    @ApiOperationSupport(order = 40)
    @PostMapping("update")
    public JsonResult update(UserUpdateParam userUpdateParam){
    //public User update(UserUpdateParam userUpdateParam){
        System.out.println("看一下"+userUpdateParam);
        User user = new User();

        BeanUtils.copyProperties(userUpdateParam,user);
        userMapper.update(user);
        //return user;
        return JsonResult.ok();
    }
}
